// 身份验证模块 - 使用数据库存储
import crypto from 'crypto';
import db from '../database.js';

// 生成随机 token
export function generateToken() {
  return crypto.randomBytes(32).toString('hex');
}

// 验证用户凭证
export function verifyCredentials(username, password) {
  const user = db.prepare('SELECT * FROM admin_users WHERE username = ?').get(username);
  if (!user) return false;
  
  const hashedPassword = crypto.createHash('sha256').update(password).digest('hex');
  return hashedPassword === user.password;
}

// 创建会话
export function createSession(username) {
  const token = generateToken();
  const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24小时过期
  
  db.prepare(`
    INSERT INTO sessions (token, username, expires_at)
    VALUES (?, ?, ?)
  `).run(token, username, expiresAt.toISOString());
  
  return token;
}

// 验证会话
export function verifySession(token) {
  const session = db.prepare(`
    SELECT * FROM sessions 
    WHERE token = ? AND expires_at > datetime('now')
  `).get(token);
  
  return !!session;
}

// 删除会话
export function destroySession(token) {
  db.prepare('DELETE FROM sessions WHERE token = ?').run(token);
}

// 生成图形验证码（简单的数学运算验证码）
export function generateCaptcha() {
  const num1 = Math.floor(Math.random() * 10) + 1;
  const num2 = Math.floor(Math.random() * 10) + 1;
  const operators = ['+', '-', '*'];
  const operator = operators[Math.floor(Math.random() * operators.length)];
  
  let answer;
  switch (operator) {
    case '+':
      answer = num1 + num2;
      break;
    case '-':
      answer = num1 - num2;
      break;
    case '*':
      answer = num1 * num2;
      break;
  }
  
  const captchaId = generateToken();
  const question = `${num1} ${operator} ${num2} = ?`;
  const expiresAt = new Date(Date.now() + 10 * 60 * 1000); // 10分钟有效
  
  // 存储验证码到数据库
  db.prepare(`
    INSERT INTO captchas (id, answer, expires_at)
    VALUES (?, ?, ?)
  `).run(captchaId, answer, expiresAt.toISOString());
  
  return { captchaId, question };
}

// 验证验证码
export function verifyCaptcha(captchaId, answer) {
  const captcha = db.prepare(`
    SELECT * FROM captchas 
    WHERE id = ? AND expires_at > datetime('now')
  `).get(captchaId);
  
  if (!captcha) return false;
  
  // 删除已使用的验证码
  db.prepare('DELETE FROM captchas WHERE id = ?').run(captchaId);
  
  return parseInt(answer) === captcha.answer;
}

// 获取会话用户信息
export function getSessionUser(token) {
  const session = db.prepare(`
    SELECT username FROM sessions 
    WHERE token = ? AND expires_at > datetime('now')
  `).get(token);
  
  return session ? session.username : null;
}

// 修改密码
export function changePassword(username, oldPassword, newPassword) {
  // 验证旧密码
  if (!verifyCredentials(username, oldPassword)) {
    return { success: false, error: '旧密码错误' };
  }
  
  // 验证新密码长度
  if (!newPassword || newPassword.length < 6) {
    return { success: false, error: '新密码长度至少6位' };
  }
  
  // 更新密码
  const hashedPassword = crypto.createHash('sha256').update(newPassword).digest('hex');
  const result = db.prepare(`
    UPDATE admin_users 
    SET password = ?, updated_at = CURRENT_TIMESTAMP
    WHERE username = ?
  `).run(hashedPassword, username);
  
  if (result.changes === 0) {
    return { success: false, error: '用户不存在' };
  }
  
  return { success: true, message: '密码修改成功' };
}

